package com.example.order;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {

    private EditText editTextUsername, editTextPassword, editTextConfirmPassword;
    private CheckBox checkBoxAgree;
    private Button buttonRegister,buttonLogin;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPassword = findViewById(R.id.editTextPassword);
        editTextConfirmPassword = findViewById(R.id.editTextConfirmPassword);
        checkBoxAgree = findViewById(R.id.checkBoxAgree);
        buttonRegister = findViewById(R.id.buttonRegister);
        buttonLogin = findViewById(R.id.buttonLogin);

        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (validateInput()) {
                    // 执行注册操作
                    new RegisterAsyncTask().execute();
                }
            }
        });

        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });

    }





    private boolean validateInput() {
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        String confirmPassword = editTextConfirmPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "密码不一致", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!checkBoxAgree.isChecked()) {
            Toast.makeText(this, "请同意注册协议", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private class RegisterAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            try {
                String username = editTextUsername.getText().toString().trim();
                String password = editTextPassword.getText().toString().trim();

                String registerUrl = "http://10.2.0.232:8080/app/addStudent";

                // 构建 JSON 请求体
                JSONObject jsonRequest = new JSONObject();
                jsonRequest.put("consumer_id", username);
                jsonRequest.put("consumer_password", password);
                String requestBody = jsonRequest.toString();

                // 使用 OkHttp 进行网络请求
                OkHttpClient client = new OkHttpClient();
                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, requestBody);
                Request request = new Request.Builder()
                        .url(registerUrl)
                        .post(body)
                        .build();

                Response response = client.newCall(request).execute();
                return response.body().string();

            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return "Error: " + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            Log.d("RegisterAsyncTask", "Raw Result: " + result);

            if (result != null && result.startsWith("Error")) {
                // 处理错误逻辑
                Log.e("RegisterAsyncTask", "Registration error: " + result);
                Toast.makeText(RegisterActivity.this, result, Toast.LENGTH_SHORT).show();
            } else {
                // 处理成功的逻辑
                try {
                    // 直接构建 JSONObject
                    JSONObject jsonResult = new JSONObject(result);

                    // 处理 JSON 数据
                    String resultStatus = jsonResult.optString("result");

                    if ("success".equals(resultStatus)) {
                        // 注册成功，处理相应逻辑
                        Toast.makeText(RegisterActivity.this, jsonResult.optString("message"), Toast.LENGTH_SHORT).show();

                        // 启动登录页面并清除之前的活动堆栈
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish(); // 结束当前注册页面
                    } else {
                        // 注册失败，处理相应逻辑
                        Toast.makeText(RegisterActivity.this, jsonResult.optString("message"), Toast.LENGTH_SHORT).show();
                        // 这里可以添加其他失败时的处理逻辑，例如显示错误消息等
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    // 在这里处理 JSONException
                    Log.e("RegisterAsyncTask", "JSON parsing error", e);
                    Toast.makeText(RegisterActivity.this, "注册失败，服务器返回异常", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }
}
